from google.appengine.ext import db
from domain import document
from repository import documentrepository
from task import basetask

class DocumentTask(basetask.BaseTask):

    def __init__(self):
        basetask.BaseTask.__init__(self)
        self._has_next = False
        self._has_prev = False

    def hasNextPage(self):
        return self._has_next

    def hasPrevPage(self):
        return self._has_prev
    
    def getNewest(self, howmany):
        repository = documentrepository.DocumentRepository()
        documents = repository.getNewest(howmany)
        self.logmessage("DocumentTask retrieved new documents, limit = " + str(howmany))
        return documents

    def getAll(self):
        repository = documentrepository.DocumentRepository()
        documents = repository.getAll()
        self.logmessage("DocumentTask retrieved all documents, limit = " + str(documents.count()))
        return documents

    def getAllByRange(self, start, howmany):
        repository = documentrepository.DocumentRepository()
        documents = repository.getAllByRange(start, howmany)
        self.logmessage("DocumentTask retrieved all documents by range, start = " + str(start) + " count = " + str(howmany))
        return documents

    def getRange(self, page, items_per_page, category=None):
        repository = documentrepository.DocumentRepository()
        documents = repository.getRange(page, items_per_page, category)
        self._has_next = repository.hasNext()
        self._has_prev = repository.hasPrev()
        self.logmessage("DocumentTask retrieved published documents by range, page = " + str(page) + ", count = " + str(items_per_page))
        return documents

    def getByCategory(self, page, items_per_page, category):
        documents = self.getRange(page, items_per_page, category)
        self.logmessage("DocumentTask retrieved published documents for category: " + str(category))
        return documents

    def getByKey(self, documentkey):
        thekey = db.Key(documentkey)
        repository = documentrepository.DocumentRepository()
        self.logmessage("DocumentTask retrieved document by key: " + str(documentkey))
        return repository.getByKey(thekey)

    def save(self, newdocument):
        if (isinstance(newdocument, document.Document)):
            repository = documentrepository.DocumentRepository()
            if (repository.save(newdocument)):
                self.logmessage("DocumentTask saved document: " + str(newdocument.title))
                return True
            else:
                self.logmessage("DocumentTask could not save document:" + str(newdocument.title))
                return False
        else:
            return False

    def delete(self, olddocument):
        if (isinstance(olddocument, document.Document)):
            repository = documentrepository.DocumentRepository()
            repository.delete(olddocument)
            self.logmessage("Document deleted: " + str(olddocument.title))

